package edu.uni.dormitory.controller;

import edu.uni.auth.bean.User;
import edu.uni.auth.service.AuthService;
import edu.uni.bean.Result;
import edu.uni.bean.ResultType;
import edu.uni.dormitory.service.StudentBedExcelService;
import edu.uni.userBaseInfo1.bean.Employee;
import edu.uni.userBaseInfo1.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

import static edu.uni.bean.ResultType.*;

/**
 * @author 陈楚城
 * @create 2019.05.03
 * @function 宿舍床位excel
 */
@Api
@RestController
@RequestMapping("json/excel")
public class StudentBedExcelController{
    @Autowired
    StudentBedExcelService studentBedExcelService;
    @Autowired
    private EmployeeService employeeService;


    @Autowired
    private AuthService authService;

    @ApiOperation("下载模板文件")
    @GetMapping("model/download")
    public ResponseEntity<byte[]> downloadStudentBedModel(HttpSession session) throws IOException {
        //获取登录人id、角色
        User user = authService.getUser();
        if(user == null) return null;
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能申请的权限
        String path = "D://ProjectTest";
        String fileName = "model.xlsx";
        File file = new File(path, fileName);

        HttpHeaders headers = new HttpHeaders();

        //下载显示的文件名，解决中文名称乱码问题
        String downloadFileName = new String(fileName.getBytes(StandardCharsets.UTF_8),
                StandardCharsets.ISO_8859_1);
        //通知浏览器以attachment（下载方式）
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        /*
          解决IE不能下载文件问题
         */
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.OK);

    }

    @ApiOperation("上传新生床位信息")
    @RequestMapping(value = "/newStudent/import", method = RequestMethod.POST)
    public Result uploadNewStudentBed(MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException {
        //获取登录人id、角色
        User user = authService.getUser();
        if(user == null) return Result.build(Failed);
        String loginId = user.getId().toString();
        //根据身份判断是否有能申请的权限
        if(file != null) {
            String savePath = request.getServletContext().getRealPath("/");
            if(studentBedExcelService.uploadNewStudentBed(savePath, file, Long.valueOf(loginId)) > 0) {
                return Result.build(Success);
            }
        }
        return Result.build(Failed);
    }

    @ApiOperation("导出宿舍区学生住宿情况")
    @GetMapping("area/export")
    public ResponseEntity<byte[]> exportAreaStudentBed(Long areaId, HttpSession session) throws IOException {
        //获取登录人id、角色
        User user = authService.getUser();
        if(user == null) return null;
        String loginId = user.getId().toString();
        List<String> roleList = user.getRoleStrlist();
        //根据身份判断是否有能申请的权限
        String path = session.getServletContext().getRealPath("/");
        String fileName = "area.xls";
        File file = studentBedExcelService.exportStudentBedByArea(areaId, path, fileName);
        ResponseEntity<byte[]> headers = downFile(fileName, file);
        if(headers != null) return headers;
        return null;
    }

    @ApiOperation("导出宿舍学生住宿情况")
    @GetMapping("room/export")
    public ResponseEntity<byte[]> exportRoomStudentBed(Long roomId, HttpSession session) throws IOException {
        String path = session.getServletContext().getRealPath("/");
        String fileName = "room.xls";
        File file = studentBedExcelService.exportStudentBedByRoom(roomId, path, fileName);
        ResponseEntity<byte[]> headers = downFile(fileName, file);
        if(headers != null) return headers;
        return null;
    }

    @ApiOperation("导出宿舍学生住宿情况")
    @GetMapping("class/export")
    public ResponseEntity<byte[]> exportClassStudentBed(Long classId, HttpSession session) throws IOException {
        String path = session.getServletContext().getRealPath("/");
        String fileName = "class.xls";
        File file = studentBedExcelService.exportStudentBedByClass(classId, path, fileName);
        ResponseEntity<byte[]> headers = downFile(fileName, file);
        if(headers != null) return headers;
        return null;
    }

    private ResponseEntity<byte[]> downFile(String fileName, File file) throws IOException {
        if(file != null){
            HttpHeaders headers = new HttpHeaders();

            //下载显示的文件名，解决中文名称乱码问题
            String downloadFileName = new String(fileName.getBytes(StandardCharsets.UTF_8),
                    StandardCharsets.ISO_8859_1);
            //通知浏览器以attachment（下载方式）
            headers.setContentDispositionFormData("attachment", downloadFileName);
            //application/octet-stream ： 二进制流数据（最常见的文件下载）。
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    /*
      解决IE不能下载文件问题
     */
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.OK);

        }
        return null;
    }

    private long getEmployeeIdByUserId(Long userId) {
        List<Employee> employeeList = employeeService.selectByUserId(Long.valueOf(userId));
        return (employeeList == null || employeeList.size() == 0) ? -1 : employeeList.get(0).getId();
    }
}
